﻿using System.Threading.Tasks;
using BookSourceVerification.utils;
using Newtonsoft.Json.Linq;
using NLog;

namespace BookSourceVerification.handlers;

class HttpVerifyHandler : IHandler<JObject>
{
    public static readonly HttpVerifyChecker HttpVerifyChecker = new();
    private Logger _logger = LogManager.GetCurrentClassLogger();

    public bool IsChecked(JObject node, HandlerResult result)
    {
        if (result.Data is string) return true;
        _logger.Error("url为空");
        return false;
    }

    /// <summary>
    /// 验证书源url是否有效
    /// </summary>
    /// <param name="node"></param>
    /// <param name="result">上一个过滤器想要传递给下一个过滤器的数据，可以为空</param>
    /// <returns></returns>
    public async Task DoHandler(JObject node, HandlerResult result)
    {
        string url = (result.Data as string)!;

        if (await HttpVerifyChecker.Check(url) == false)
        {
            result.Fail();
        }
        else
        {
            result.Success(url);
        }
    }

    public void AfterHandler()
    {
    }

    public void SetHttpClientTimeout()
    {
        HttpVerifyChecker.SetHttpClientTimeout();
    }
}